package com.project_doctor.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.project_doctor.exception.SystemCode;
import com.project_doctor.handler.dropped.IntegerListConverter;
import com.project_doctor.pojo.AnnouncementReply;
import com.project_doctor.pojo.Dto.AnnRequest;
import com.project_doctor.pojo.Dto.AnnouncementReplyDTO;
import com.project_doctor.pojo.SystemAnnouncement;
import com.project_doctor.service.AnnouncementReceiverService;
import com.project_doctor.service.AnnouncementReplyService;
import com.project_doctor.service.SystemAnnouncementService;
import com.project_doctor.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@Slf4j
@RestController
@RequestMapping("announcement")
public class AnnouncementController {
    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private RedisTemplate redisTemplate;

    //注入Rabbit模板类
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private SystemAnnouncementService systemAnnouncementService;

    @Autowired
    private AnnouncementReplyService announcementReplyService;

    @Autowired
    private AnnouncementReceiverService announcementReceiverService;


    @GetMapping("/getAnnById/{id}")
    public ResponseEntity<?> getAnnById(@PathVariable Long id) {
        SystemAnnouncement systemAnnouncement = systemAnnouncementService.getAnnById(id);
        return ResponseEntity.ok(systemAnnouncement);
    }
    @PostMapping("/getAnnouncementList")
    public ResponseEntity<?> getAnnouncementList(@RequestBody(required = false) AnnRequest annRequest) {
        List<SystemAnnouncement> list = systemAnnouncementService.getAnnouncementList(annRequest);
        return ResponseEntity.ok(list);
    }

    @PutMapping("/updateAnnouncement")
    public ResponseEntity<?> updateAnnouncement(@RequestBody SystemAnnouncement systemAnnouncement) {

        systemAnnouncementService.updateAnnouncement(systemAnnouncement);

        return ResponseEntity.ok(SystemCode.SUCCESS_Edit_ANNOUNCEMENT.getMessage());
    }
    @PostMapping("/newAnnouncement")
    public ResponseEntity<?> newAnnouncement(@RequestBody SystemAnnouncement systemAnnouncement) {
        systemAnnouncementService.newAnnouncement(systemAnnouncement);
        return ResponseEntity.ok(SystemCode.SUCCESS_NEW_ANNOUNCEMENT.getMessage());
    }

    @DeleteMapping("/deleteAnnouncement/{id}")
    public ResponseEntity<?> deleteAnnouncement(@PathVariable Long id) {
        systemAnnouncementService.removeById(id);
        return ResponseEntity.ok(SystemCode.SUCCESS_DELETE_ANNOUNCEMENT.getMessage());

    }

//    @GetMapping("/download")
//    public void download(HttpServletResponse response) throws IOException {
//        try {
//            // 设置正确的响应头
//            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//            response.setCharacterEncoding("utf-8");
//
//            // 修正Content-disposition头部格式
//            String fileName = URLEncoder.encode("公告数据", "UTF-8").replaceAll("\\+", "%20");
//            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
//
//            // 查询数据
//            List<SystemAnnouncement> list = systemAnnouncementService.list();
//
//            // 创建Excel写入器并注册转换器
//            EasyExcel.write(response.getOutputStream(), SystemAnnouncement.class)
//                    .registerConverter(new IntegerListConverter()) // 注册List<Integer>转换器
//                    .sheet("模板")
//                    .doWrite(list);
//        } catch (Exception e) {
//            // 错误处理
//            response.reset(); // 重置响应
//            response.setContentType("text/plain");
//            response.setCharacterEncoding("utf-8");
//            response.getWriter().write("导出失败: " + e.getMessage());
//            e.printStackTrace();
//        }
//    }

    @GetMapping("/download")
    public ResponseEntity<?> download() {
        try {
            // 查询数据
            List<SystemAnnouncement> list = systemAnnouncementService.getAnnouncementList(null);

            // 创建临时文件
            File tempFile = File.createTempFile("announcements", ".xlsx");
            tempFile.deleteOnExit();

            // 写入Excel到临时文件
            EasyExcel.write(tempFile, SystemAnnouncement.class)
                    .registerConverter(new IntegerListConverter())
                    .sheet("模板")
                    .doWrite(list);

            // 创建文件资源
            Resource resource = new FileSystemResource(tempFile);

            // 设置响应头
            String fileName = URLEncoder.encode("公告数据", "UTF-8").replaceAll("\\+", "%20");
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + fileName + ".xlsx");

            return ResponseEntity.ok()
                    .headers(headers)
                    .contentLength(resource.contentLength())
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource);
        } catch (Exception e) {
            // 返回错误响应
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "导出失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    @PostMapping("/upload")
    public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("请上传文件");
        }
        EasyExcel.read(file.getInputStream(), SystemAnnouncement.class, new PageReadListener<SystemAnnouncement>(dataList -> {
            systemAnnouncementService.batchNewAnnouncement(dataList);
        })).sheet().doRead();
        return ResponseEntity.ok(SystemCode.SUCCESS_UPLOAD_ANNOUNCEMENT.getMessage());
    }

    @GetMapping("/listForReceiver")
    public ResponseEntity<?> listForReceiver(@RequestParam Long receiverId,
                                  @RequestParam(required = false) Integer status) {


        List<SystemAnnouncement> systemAnnouncements = systemAnnouncementService.listForReceiver(receiverId, status);
        return ResponseEntity.ok(systemAnnouncements);
    }

    @PostMapping("/markAsRead")
    public ResponseEntity<?> markAsRead(@RequestParam Long announcementId,
                             @RequestParam Long receiverId) {
        announcementReceiverService.markAsRead(announcementId, receiverId);
        return ResponseEntity.ok(SystemCode.SUCCESS_MARKASREAD_ANNOUNCEMENT.getMessage());
    }

    @PostMapping("/addReply")
    public ResponseEntity<?> addReply(@RequestBody AnnouncementReplyDTO dto) {
        Long replyId = announcementReplyService.addReply(dto);
        return ResponseEntity.ok(replyId);
    }

    @GetMapping("/listReplies")
    public ResponseEntity<?> listReplies(@RequestParam Long announcementId) {
        List<AnnouncementReply> announcementReplies = announcementReplyService.listReplies(announcementId);
        return ResponseEntity.ok(announcementReplies);
    }
}
